<!-- eslint-disable vue/no-mutating-props -->
<template>
  <div class="display-search-div">
    <div class="header">
      <slot name="header"></slot>
    </div>
    <el-form class="display-search-form" ref="elformRef" :model="modelValue">
      <el-row>
        <template v-for="item in subSearchProps" :key="item.label">
          <el-col
            v-bind="item.colLayout || colLayout"
            v-if="
              !(item.vIf === false || (Object.keys(item)?.includes('vIf') && !item.vIf)) &&
              (!showToggle || !item.defaultHidden || isToggle)
            "
            :rules="item.rules"
          >
            <el-form-item
              v-if="!item.isHidden"
              :label="item.label"
              :rules="item.rules"
              :style="item.itemStyle || itemStyle"
              :label-width="item.labelWidth || finalLableWidth"
              :prop="item.field"
            >
              <template v-if="item.type === 'input' || item.type === 'password'">
                <el-input
                  :placeholder="item.placeholder ?? (!item.disabled ? '请输入' + item.label : '')"
                  :disabled="item.disabled"
                  v-bind="item.otherOptions"
                  :show-password="item.type === 'password'"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="item.type === 'select'">
                <el-select
                  clearable
                  popper-class="detailselect"
                  :placeholder="item.placeholder ?? (!item.disabled ? '请选择' + item.label : '')"
                  :disabled="item.disabled"
                  v-bind="item.otherOptions"
                  style="width: 100%"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                >
                  <el-option
                    v-for="option in codeCollection[`${item.field}`] || []"
                    :key="option.value"
                    :value="option.value"
                    :label="option.title"
                  ></el-option>
                </el-select>
              </template>
              <template v-else-if="item.type === 'supersearch'">
                <AsyncSuperSearch
                  :disabled="item.disabled"
                  :config="item.config"
                  v-model="modelValue[`${item.field}`]"
                  style="width: 100%"
                ></AsyncSuperSearch>
              </template>
              <template v-else-if="item.type === 'datepicker'">
                <el-date-picker
                  style="width: 100%"
                  v-bind="item.otherOptions"
                  :model-value="modelValue[`${item.field}`]"
                  @update:modelValue="handleValueChange($event, item.field)"
                ></el-date-picker>
              </template>
              <template v-else-if="item.type === 'checkboxgroup'">
                <el-checkbox-group
                  :model-value="modelValue[`${item.field}`]"
                  v-bind="item.otherOptions"
                  :disabled="item.disabled"
                  @update:modelValue="handleValueChange($event, item.field)"
                  style="width: 100%"
                >
                  <el-checkbox v-for="option in codeCollection[`${item.field}`]" :key="option.value" :label="option.value">{{
                    option.title
                  }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <div class="footer">
      <slot name="footer"></slot>
    </div>
  </div>
</template>

<script>
import { ref, defineAsyncComponent } from "vue";
const AsyncSuperSearch = defineAsyncComponent(() => import("@/components/SuperSearch/index.vue"));
export default {
  components: {
    AsyncSuperSearch
  },
  props: {
    modelValue: {
      type: Object,
      required: true
    },
    searchProps: {
      type: [Array, Function],
      default: () => []
    },
    labelWidth: {
      type: String,
      default: undefined
    },
    itemStyle: {
      type: Object,
      default: () => ({ padding: "10px 40px", marginBottom: "1px" })
    },
    colLayout: {
      type: Object,
      default: () => ({
        span: 12
      })
    }
  },
  emits: ["update:modelValue"],
  setup(props, { emit }) {
    const elformRef = ref(null);
    const showToggle = ref(false); //是否展示折叠搜索条件
    //const isToggle = ref(false); //折叠状态,默认是false,收起的
    const codeCollection = ref({});
    const finalLableWidth = ref("");

    const subSearchProps = ref([]);
    const apendCodeAndJudgeShowToggle = async () => {
      debugger;
      //1.参数归一化
      let propList = [];
      if (props.searchProps instanceof Array) {
        propList = props.searchProps;
      } else if (typeof props.searchProps === "function") {
        propList = await props.searchProps(props.modelValue);
      }
      //2.如果用户没有指定labelWidth,则计算一个默认值，默认值取所有label的最大值
      if (props.labelWidth) {
        finalLableWidth.value = props.labelWidth;
      } else {
        //取出表单中的label，取出最大长度的label作为所有label的长度
        let maxLabelLength = propList.map(item => item.label).reduce((a, b) => (a.length > b.length ? a : b)).length;
        maxLabelLength * 14 < 80 ? (maxLabelLength = 80) : (maxLabelLength = maxLabelLength * 14);
        let finalLabelWidth = maxLabelLength + "px";
        finalLableWidth.value = finalLabelWidth;
      }
      //2.将props赋值给subSearchProps(子组件自己的配置信息)
      subSearchProps.value = propList;
      //3
      for (const item of propList) {
        //3.1.处理required和rules的关系
        if (item.rules && !item.required) {
        } else if (item.rules && item.required) {
          //判断rules是否有required
          if (!item.rules.some(item => item.required)) {
            item.rules = [...item.rules, { required: true, message: `${item.label}不能为空`, trigger: "blur" }];
          }
        } else if (!item.rules && item.required) {
          item.rules = [{ required: true, message: `${item.label}不能为空`, trigger: "blur" }];
        } else {
          item.rules = [];
        }
        //3.2 处理span和colLayout的关系
        item.colLayout = item.colLayout || { span: item.span || 12 };
        //3.3. 加载code数据
        if (item.type === "select" || item.type === "checkboxgroup") {
          let options = item.options || item.codeMap;
          if (options instanceof Array) {
            codeCollection.value[`${item.field}`] = options;
          } else if (typeof options === "function") {
            debugger;
            codeCollection.value[`${item.field}`] = (await options()) || [];
            debugger;
          }
        }
      }
    };
    const handleValueChange = (value, field) => {
      emit("update:modelValue", { ...props.modelValue, [field]: value });
    };
    apendCodeAndJudgeShowToggle();
    return {
      handleValueChange,
      codeCollection,
      elformRef,
      showToggle,
      subSearchProps,
      finalLableWidth
    };
  }
};
</script>
<style scoped>
:deep() .el-form-item__content {
  flex-wrap: nowrap;
}
.display-search-div {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.footer {
  margin-top: auto;
}
</style>
